package com.pea;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class Main2 {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Hello world!");
        ExecutorService executorService =
        new ThreadPoolExecutor(3, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
        CountDownLatch countDownLatch = new CountDownLatch(5);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            executorService.submit(() -> {
                try {
                    //finalI = finalI + 1;
                    System.out.println("当前线程" + Thread.currentThread().getName() + "正在执行任务" + finalI + "开始执行");
                    List<String> arrayList = getDataFromDB();
                    CountDownLatch countDownLatchSub = new CountDownLatch(arrayList.size());
                    for (String s : arrayList) {
                        syncHandleData(finalI, s, executorService, countDownLatchSub);
                    }
                    countDownLatchSub.await();
                    System.out.println("当前线程" + Thread.currentThread().getName() + "正在执行任务" + finalI + "任务执行完毕");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        long times = System.currentTimeMillis() - start;
        System.out.println(times);
    }

    private static List<String> getDataFromDB() {
        List<String> arrayList = new ArrayList<>();
        arrayList.add("1");
        arrayList.add("2");
        return arrayList;
    }

    private static CompletableFuture<String> syncHandleData(int finalI, String str, ExecutorService executorService, CountDownLatch countDownLatchSub) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println("当前线程" + Thread.currentThread().getName() + "正在执行任务" + finalI + "正在处理数据=" + str);
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                countDownLatchSub.countDown();
            }
            return "处理数据" + str + "成功";
        }, executorService);
    }
}